/*
 * Copyright (c) 2008-2009, Computational Crawling LP
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 *    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *    * Neither the name of Computational Crawling LP, 80legs, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.eightylegs.customer.default80legs;

import java.util.ArrayList;


/**
 * Class CrawlSelectData.
 * 
 * This represents the data provided by the users.  It is a list of ContentSelectUserItem and a return type. 
 */
public class CrawlSelectData 
{
	private static int MAX_STRING_COUNT = 1000;
	
	public static byte CSD_REGEX = 0; 
	public static byte CSD_SIMPLE = 1;

	public static int CSD_COUNTMATCHES = 0;
	public static int CSD_BOOLEANARRAY = 1;
	public static int CSD_COUNTARRAY = 2;

	private ArrayList<ContentSelectUserItem> userItems;
	private int returnType;

	/**
	 *  Constructor to create the complete object with pre-computed items
	 *   
	 * @param inItems  The user's items for this data
	 * @param inReturnType  The user's return type
	 * 
	 */
	public CrawlSelectData ( ArrayList<ContentSelectUserItem> inItems, int inReturnType )
	{
		returnType = inReturnType;
		userItems = inItems;
	}
	
	/**
	 *  Constructor to create an incomplete object without any items
	 *   
	 * @param inReturnType  The user's return type
	 * 
	 */
	private CrawlSelectData( int inReturnType )
	{
		userItems = new ArrayList<ContentSelectUserItem>();
		returnType = inReturnType;
	}

	/**
	 *  Returns this entire object serialized as a byte[]
	 *   
	 * 
	 * @return   Returns this entire object serialized as a byte[]
	 */
	public byte[] serializeData() throws Exception
	{
		ArrayList<byte[]> userByteArrays = new ArrayList<byte[]>(userItems.size());
		int totalSize = 8;
		for ( ContentSelectUserItem curItem : userItems )
		{
			byte[] stringBytes = ClientUtility.stringToByteArray(curItem.GetString());
			userByteArrays.add(stringBytes);
			totalSize += 5+stringBytes.length;
		}
		
		int numItems = userItems.size();
		byte[] results = new byte[totalSize];
		ClientUtility.intToByteArray(returnType, results, 0);
		ClientUtility.intToByteArray(numItems, results, 4);

		int startByte = 8;
		for ( int iitem = 0; iitem < numItems; iitem++ )
		{
			ContentSelectUserItem curItem = userItems.get(iitem);
			byte[] stringBytes = userByteArrays.get(iitem);
			
			if ( curItem.IsRegex() == true )
				results[startByte++] = CSD_REGEX;
			else
				results[startByte++] = CSD_SIMPLE;
			ClientUtility.intToByteArray(stringBytes.length, results, startByte);
			startByte += 4;
			System.arraycopy(stringBytes, 0, results, startByte, stringBytes.length);
			startByte += stringBytes.length;
		}
		
		return results;
	}
	
	/**
	 * this function deserializes the CONTENTSTRINGS that the user has uploaded
	 * and stuffs it into a CrawlSelectData object format of data is
	 * <RETURNTYPE><NUMDATA><TYPE><CONTENTSIZE><CONTENTS> etc (repeating
	 * <TYPE><CONTENTSIZE><CONTENTS> as much as needed) <TYPE> is one byte
	 * <RETURNTYPE>, <CONTENTSIZE> and <NUMDATA> are int <CONTENTS> is an encoded String
	 *   
	 * @param data  the data to be deserialized
	 * 
	 * @return a full CrawlSelectData object created from the data
	 * 
	 */
	public static CrawlSelectData deserializeData(byte[] data) throws Exception {

		if (data.length <= 16) {
			return new CrawlSelectData(CrawlSelectData.CSD_COUNTMATCHES);
		}

		int returnType = ClientUtility.byteArrayToInt(data, 0);
		int numData = ClientUtility.byteArrayToInt(data, 4);
		CrawlSelectData tmpData = new CrawlSelectData(returnType);

		// scan out each select to do
		int byteStart = 8;
		for (int idata = 0; idata < numData; idata++) {
			if (byteStart + 5 > data.length) {
				break;
			}

			byte dataType = data[byteStart];
			int contentSize = ClientUtility.byteArrayToInt(data, byteStart + 1);
			if (byteStart + 5 + contentSize > data.length)
				break;

			try {
				String contents = ClientUtility.byteArrayToString(data,
						byteStart + 5, contentSize);
				tmpData.AddData(dataType, contents);
			} catch (Exception e) {
				// skip that string
			}
			byteStart += 5 + contentSize;
		}

		return tmpData;
	}
	
	/**
	 * returns the user's return type
	 *   
	 * @return returns the user's return type
	 * 
	 */
	public int GetReturnType()
	{
		return returnType;
	}
	
	/**
	 * Add's an item to the list of items
	 *   
	 * @param dataType  CSD_REGEX or CSD_STRING
	 * @param inString  the item data
	 * 
	 */
	public void AddData ( byte dataType, String inString )
	{
		if ( userItems.size() > MAX_STRING_COUNT )
			return;
		boolean isRegex = false;
		if ( dataType == CSD_REGEX )
			isRegex = true;
		userItems.add ( new ContentSelectUserItem ( inString, isRegex ) );
	}

	/**
	 * Returns all of the items
	 *   
	 * @return returns all of the items
	 * 
	 */
	public ArrayList<ContentSelectUserItem> GetItems()
	{
		return userItems;
	}
	
	/**
	 * returns the number of items
	 *   
	 * @return the number of items
	 * 
	 */
	public int GetItemCount()
	{
		return userItems.size();
	}
}
